// ------------------------------------
// Actions
// ------------------------------------
import { createAction } from 'http-services'
import * as types from './constant'
import { HttpServices, REDUX_FETCH_TIMEOUT } from 'services/utils'
import * as storageService from 'services/storage'
import _ from 'lodash'
import fetchMock from 'fetch-mock'
import { getToken, setToken } from 'services/token'
import qs from 'query-string'

export const getlist = () => dispatch => {
  dispatch(createAction(types.PROTO_FETCH_GETLIST_BEGIN, null))
  setTimeout(() => new Promise(async (resolve, reject) => {
    try {
      const token = getToken()
      const header = {
        Authorization: token
      }
      const result = await HttpServices.GET(`/proto`, null, header)
      fetchMock.restore()
      dispatch(createAction(types.PROTO_FETCH_GETLIST_SUCCESS, result))
      resolve(result)
    } catch (error) {
      dispatch(createAction(types.PROTO_FETCH_GETLIST_FAILURE, error))
      reject(error)
    }
  })
  .catch(() => {}), REDUX_FETCH_TIMEOUT)
}

export const postData = (proto, options = null, rtsp_key = undefined) => dispatch => {
  dispatch(createAction(types.PROTO_FETCH_POSTDATA_BEGIN, { proto, options }))
  setTimeout(() => new Promise(async (resolve, reject) => {
    try {
      const token = getToken()
      const header = {
        Authorization: token,
        rtsp_key
      }
      const result = await HttpServices.POST(`/proto/${proto}`, options, header)
      fetchMock.restore()
      dispatch(createAction(types.PROTO_FETCH_POSTDATA_SUCCESS, result))
      resolve(result)
    } catch (error) {
      dispatch(createAction(types.PROTO_FETCH_POSTDATA_FAILURE, error))
      reject(error)
    }
  })
  .catch(() => {}), REDUX_FETCH_TIMEOUT)
}

export const stopData = () => dispatch => dispatch(createAction(types.PROTO_FETCH_POSTDATA_STOP, null))